package com.ruoyi.work.controller;

import java.sql.Timestamp;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.work.domain.TbEquTrain;
import com.ruoyi.work.domain.TbWorkOrderUser;
import com.ruoyi.work.service.ITbEquTrainService;
import com.ruoyi.work.service.ITbWorkOrderUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.work.domain.TbWorkOrder;
import com.ruoyi.work.service.ITbWorkOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 救援任务Controller
 *
 * @author szm
 * @date 2025-10-21
 */
@Api(tags = "救援任务")
@RestController
@RequestMapping("/work/TbWorkOrder")
public class TbWorkOrderController extends BaseController {
    @Autowired
    private ITbWorkOrderService tbWorkOrderService;
    @Autowired
    private ITbEquTrainService tbEquTrainService;
    @Autowired
    private ITbWorkOrderUserService tbWorkOrderUserService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询救援任务列表
     */
    @ApiOperation("查询救援任务列表")
    @GetMapping("/list")
    public TableDataInfo list(TbWorkOrder entity, HttpServletRequest req) {
        startPage();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.setEntity(entity);
        List<TbWorkOrder> list = tbWorkOrderService.list(wrapper);
        return getDataTable(list);
    }

    /**
     * 导出救援任务列表
     */
    @ApiOperation("导出救援任务列表")
    @Log(title = "救援任务", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(HttpServletResponse response, TbWorkOrder entity) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.setEntity(entity);
        List<TbWorkOrder> list = tbWorkOrderService.list(wrapper);
        ExcelUtil<TbWorkOrder> util = new ExcelUtil<TbWorkOrder>(TbWorkOrder.class);
        util.exportExcel(response, list, "救援任务数据");
    }

    /**
     * 获取救援任务详细信息
     */
    @ApiOperation("获取救援任务详细信息")
    @GetMapping(value = "/getById")
    public AjaxResult getById(@RequestParam("id") String id) {
        return success(tbWorkOrderService.getById(id));
    }

    /**
     * 新增救援任务
     */
    @ApiOperation("新增/修改救援任务")
    @Log(title = "救援任务", businessType = BusinessType.INSERT)
    @PostMapping("/save")
    public AjaxResult save(TbWorkOrder entity) {
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        return toAjax(tbWorkOrderService.saveOrUpdate(entity));
    }

    /**
     * 开始救援任务
     */
    @ApiOperation("开始救援任务")
    @Log(title = "开始救援任务", businessType = BusinessType.INSERT)
    @PostMapping("/start")
    public AjaxResult start(@RequestBody TbWorkOrder entity) {
        entity.setStartTime(new Date());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        boolean b = tbWorkOrderService.saveOrUpdate(entity);
        String[] split = entity.getTrainNo().split(",");
        List<TbEquTrain> equTrains = tbEquTrainService.lambdaQuery().in(TbEquTrain::getTrainNo, split).list();
        if (b) {
            for (TbEquTrain train : equTrains) {
                redisCache.deleteObject(CacheConstants.WORK_NO + train.getEquNo());
                redisCache.setCacheObject(CacheConstants.WORK_NO + train.getEquNo(), entity);
            }
            redisCache.setCacheObject(entity.getWorkNo(), entity.getWorkNo());

           /* List<TbWorkOrderUser> orderUserList = new LinkedList<>();
            List<SysUser> list = sysUserService.list();
            for (SysUser user : list) {
                if (user.getUserName() != "admin" && user.getUserName() != "sysadmin") {
                    TbWorkOrderUser orderUser = new TbWorkOrderUser();
                    orderUser.setWorkNo(entity.getWorkNo());
                    orderUser.setUserNo(user.getUserName());
                    orderUser.setUserName(user.getNickName());
                    orderUser.setStatus("1");
                    orderUser.setCreateTime(new Date());
                    orderUser.setUpdateTime(new Date());
                    orderUser.setPhone(user.getPhonenumber());
                    orderUserList.add(orderUser);
                }
            }

            tbWorkOrderUserService.saveOrUpdateBatch(orderUserList);*/
        }
        return toAjax(b);
    }

    /**
     * 结束救援任务
     */
    @ApiOperation("结束救援任务")
    @Log(title = "结束救援任务", businessType = BusinessType.INSERT)
    @PostMapping("/end")
    public AjaxResult end(@RequestBody TbWorkOrder entity) {
        entity.setStatus("2");
        entity.setUserName(SecurityUtils.getUsername());
        entity.setEndTime(new Date());
        entity.setUpdateTime(new Date());
        boolean b = tbWorkOrderService.updateById(entity);
        if (b) {
            String[] split = entity.getTrainNo().split(",");
            List<TbEquTrain> equTrains = tbEquTrainService.lambdaQuery().in(TbEquTrain::getTrainNo, split).list();
            for (TbEquTrain train : equTrains) {
                redisCache.deleteObject(CacheConstants.WORK_NO + train.getEquNo());
            }
            redisCache.deleteObject(entity.getWorkNo());
            List<TbWorkOrderUser> userList = tbWorkOrderUserService.lambdaQuery().eq(TbWorkOrderUser::getWorkNo, entity.getWorkNo()).list();
            if (CollectionUtil.isNotEmpty(userList)){
                for (TbWorkOrderUser user : userList){
                    redisCache.deleteObject(user.getUserNo());
                }
            }
            tbWorkOrderUserService.updateByWorkNo(entity.getWorkNo());

        }
        return AjaxResult.success();
    }

    /**
     * 删除救援任务
     */
    @ApiOperation("删除救援任务")
    @Log(title = "救援任务", businessType = BusinessType.DELETE)
    @PostMapping("/delIds")
    public AjaxResult remove(@RequestParam("ids") String ids) {
        return toAjax(tbWorkOrderService.removeById(ids));
    }
}
